package cn.xeblog.server.util;

import cn.hutool.core.thread.GlobalThreadPool;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import cn.xeblog.commons.entity.*;
import cn.xeblog.commons.util.LocalLogUtils;
import cn.xeblog.server.cache.UserCache;
import cn.xeblog.server.config.ServerConfig;
import lombok.extern.slf4j.Slf4j;

/**
 * 功能描述:
 *
 * @author ZhangLei
 * @date 2022/10/14 15:39
 */
@Slf4j
public class ServerLogUtils extends LocalLogUtils {

//    private static final String DOMAIN = "http://47.96.115.18:8180";
//    private static final String DOMAIN = "http://172.22.208.1:8180";

    public static void saveResponseToLocalFile(Response response) {
        LocalLogUtils.saveResponse(response);
        Object body = response.getBody();
        if (body instanceof UserStateMsgDTO) {
            sendMessageToMySystem((UserStateMsgDTO) body);
        }
    }

    public static void sendMessageToMySystem(UserStateMsgDTO userMsgDTO) {
        String xeUserDomain = ServerConfig.getConfig().getXeUserDomain();
        if (StrUtil.isEmpty(xeUserDomain)) {
            return;
        }

        GlobalThreadPool.execute(() -> {
            try {
                XEUser xeUser = IpUtil.convertXEUser(userMsgDTO);
                // 本地登录不再记录
                if ("127.0.0.1".equals(xeUser.getIp())) {
                    return;
                }
                String url = xeUserDomain + "/xeUser/add";
                String response = HttpUtil.post(url, JSONUtil.toJsonStr(xeUser));
                log.info("请求回执：{}", response);

                if (UserStateMsgDTO.State.OFFLINE == userMsgDTO.getState()) {
                    return;
                }

                XEUser xeUserResponse = JSONUtil.parseObj(response).getJSONObject("data").toBean(XEUser.class);
                User user = UserCache.getUserByUsername(xeUserResponse.getUsername());
                if (user != null) {
                    user.setOnLineId(xeUserResponse.getId());
                }
            } catch (Exception e) {
                log.error("请求失败了！", e);
            }
        });
    }

    public static void sendFileRecordToMySystem(User user, UserMsgDTO dto) {
        String xeUserDomain = ServerConfig.getConfig().getXeUserDomain();
        if (StrUtil.isEmpty(xeUserDomain)) {
            return;
        }

        GlobalThreadPool.execute(() -> {
            try {
                Long onLineId = user.getOnLineId();
                String fileName = String.valueOf(dto.getContent());
                if (onLineId == null) {
                    log.info("用户[{}]发了一个文件[{}]，记录未提交到FlySystem", user.getUsername(), fileName);
                    return;
                }

                XEUser xeUser = new XEUser();
                xeUser.setId(onLineId);
                XeUserFileRecord xeUserFileRecord = new XeUserFileRecord();
                xeUserFileRecord.setFileName(fileName);
                xeUserFileRecord.setXeUser(xeUser);

                String url = xeUserDomain + "/xeUser/file/record/add";
                String response = HttpUtil.post(url, JSONUtil.toJsonStr(xeUserFileRecord));
                log.info("请求回执：{}", response);

            } catch (Exception e) {
                log.error("请求失败了！", e);
            }
        });
    }

}
